<!-- 登录页面 -->
<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <h2 class="login-title">在线考试系统</h2>
      </template>

      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="0"
      >
        <el-form-item prop="username">
          <el-input
            v-model.trim="loginForm.username"
            placeholder="用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model.trim="loginForm.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
            @keyup.enter="handleLogin"
          />
        </el-form-item>

        <el-form-item prop="captcha">
          <div class="captcha-container">
            <el-input
              v-model.trim="loginForm.captcha"
              placeholder="验证码"
              style="width: 200px"
            />
            <canvas
              ref="captchaCanvas"
              width="120"
              height="40"
              @click="refreshCaptcha"
              style="cursor: pointer; margin-left: 10px"
            ></canvas>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            :loading="loading"
            class="login-button"
            @click="handleLogin"
          >
            登录
          </el-button>
        </el-form-item>

        <div class="login-options">
          <router-link to="/register">注册账号</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { User, Lock } from "@element-plus/icons-vue";
import { login } from "@/api/user";

const router = useRouter();
const loading = ref(false);
const loginFormRef = ref(null);
const loginForm = reactive({
  username: "",
  password: "",
  captcha: "",
});

const loginRules = {
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  captcha: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

// 验证码相关
const captchaCanvas = ref(null);
const captchaText = ref("");

// 生成随机验证码
const generateCaptcha = () => {
  const canvas = captchaCanvas.value;
  const ctx = canvas.getContext("2d");

  // 清空画布
  ctx.fillStyle = "#f0f2f5";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  // 生成随机验证码
  const characters =
    "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
  let code = "";
  for (let i = 0; i < 4; i++) {
    const char = characters[Math.floor(Math.random() * characters.length)];
    code += char;

    // 随机颜色
    ctx.fillStyle = `rgb(${Math.random() * 100 + 50}, ${
      Math.random() * 100 + 50
    }, ${Math.random() * 100 + 50})`;
    ctx.font = "bold 24px Arial";

    // 随机旋转
    const rotation = (Math.random() - 0.5) * 0.3;
    ctx.save();
    ctx.translate(30 * i + 15, 25);
    ctx.rotate(rotation);
    ctx.fillText(char, 0, 0);
    ctx.restore();
  }

  // 添加干扰线
  for (let i = 0; i < 3; i++) {
    ctx.strokeStyle = `rgb(${Math.random() * 200}, ${Math.random() * 200}, ${
      Math.random() * 200
    })`;
    ctx.beginPath();
    ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
    ctx.stroke();
  }

  // 添加干扰点
  for (let i = 0; i < 30; i++) {
    ctx.fillStyle = `rgb(${Math.random() * 200}, ${Math.random() * 200}, ${
      Math.random() * 200
    })`;
    ctx.beginPath();
    ctx.arc(
      Math.random() * canvas.width,
      Math.random() * canvas.height,
      1,
      0,
      2 * Math.PI
    );
    ctx.fill();
  }

  captchaText.value = code;
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
};

// 验证码校验
const validateCaptcha = () => {
  if (loginForm.captcha.toLowerCase() !== captchaText.value.toLowerCase()) {
    ElMessage.error("验证码错误");
    return false;
  }
  return true;
};

// 修改登录处理函数
const handleLogin = async () => {
  if (!loginFormRef.value) return;

  try {
    await loginFormRef.value.validate();

    // 验证码校验
    if (!validateCaptcha()) {
      refreshCaptcha();
      loginForm.captcha = "";
      return;
    }

    loading.value = true;
    const data = await login(loginForm);
    if (data) {
      localStorage.setItem("token", data.token);
      localStorage.setItem("username", data.userName);
      localStorage.setItem("userRole", data.role);
      ElMessage.success("登录成功");
      await router.push("/");
    } else {
      ElMessage.error("登录失败：返回数据格式错误");
    }
  } catch (error) {
    if (error?.response?.data?.message) {
      ElMessage.error(error.response.data.message);
    } else {
      console.error("登录失败：", error);
      ElMessage.error("登录失败，请重试");
    }
  } finally {
    loading.value = false;
  }
};

// 组件挂载时生成验证码
onMounted(() => {
  generateCaptcha();
});
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f0f2f5;
}

.login-card {
  width: 400px;
}

.login-title {
  text-align: center;
  margin: 0;
  color: #303133;
}

.login-button {
  width: 100%;
}

.login-options {
  margin-top: 20px;
  text-align: right;
}

.login-options a {
  color: #409eff;
  text-decoration: none;
}

.login-options a:hover {
  color: #66b1ff;
}

.captcha-container {
  display: flex;
  align-items: center;
}
</style>
